<?php

namespace backend\models;

use Yii;
use yii\web\UploadedFile;
use backend\helpers\FileNameInflector;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "donor".
 *
 * @property int $id
 * @property string|null $name
 * @property string|null $description
 *
 * @property Contract[] $contracts
 */
class Donor extends \yii\db\ActiveRecord
{
    const BUCKET_NAME = 'ogikm-coop-contracts';

    public $docCoopContract;
    
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'donor';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name'], 'required'],
            [['name', 'coop_contract_filename'], 'string', 'max' => 255],
            [['name'], 'unique'],
            [['description', 'coop_contract_subject'], 'string', 'max' => 512],
            [['docCoopContract'], 'file', 'extensions' => 'doc, docx, pdf', 'maxSize' => 1024*1024*10],
            [['coop_contract_date_sign', 'coop_contract_date_end'], 'safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Название',
            'description' => 'Описание',
            'coop_contract_filename' => 'Договор сотрудничества',
            'coop_contract_date_sign' => 'Дата подписания договора сотрудничества',
            'coop_contract_date_end' => 'Дата завершения договора сотрудничества',
            'coop_contract_subject' => 'Предмет договора сотрудничества',
            'docCoopContract' => 'Договор сотрудничества',
        ];
    }

    /**
     * Gets query for [[Contracts]].
     *
     * @return \yii\db\ActiveQuery
     */
    public function getContracts()
    {
        return $this->hasMany(Contract::className(), ['id_donor' => 'id']);
    }

    public static function donorList()
    {
        return ArrayHelper::map(
            self::find()->select(['name','id'])->asArray()->all(), 
            'id', 
            'name'
        );
    }

    public function beforeSave($insert)
    {
        if (!parent::beforeSave($insert)) {
            return false;
        }

        // Запись новая
        if($insert)
        {
            // Спокойно сохраняем все файлы
            $this->insertContract();
        }
        // Запись обновляется
        else
        {
            // Необходимы дополнительные проверки
            $this->updateContract();
        }
        
        return true;
    }

    public function beforeDelete()
    {
        if (!parent::beforeDelete()) {
            return false;
        }

        $this->deleteContract();

        return true;
    }

    private function insertContract()
    {
        if($this->docCoopContract) $this->coop_contract_filename = $this->uploadFile($this->docCoopContract, 'Договор сотрудничества - ' . FileNameInflector::specialSlug($this->name));
    }

    private function updateContract()
    {
        //если есть запись в БД и поле измененено - удалять
        if($this->docCoopContract) 
        { 
            if($this->coop_contract_filename)
            {
                $this->deleteFile($this->coop_contract_filename);
            }
            $this->coop_contract_filename = $this->uploadFile($this->docCoopContract, 'Договор сотрудничества - ' . $this->name);
        }
    }

    private function deleteContract()
    {
        $this->deleteFile($this->coop_contract_filename);
    }

    private function uploadFile($file, $fileName = null)
    {
        if($fileName != null)
        {
            $fileName = $fileName . '.' . $file->extension;
        }
        else
        {
            $fileName = $file->name;
        }

        if($file)
        {
            $s3 = Yii::$app->get('s3');
            $result = $s3->commands()->upload($fileName, $file->tempName)->inBucket(self::BUCKET_NAME)->withAcl('private')->execute();
            return $fileName;
        }
        else 
        {
            return null;
        }
    }

    private function deleteFile($fileName)
    {
        if($fileName)
        {
            $s3 = Yii::$app->get('s3');
            $s3->commands()->delete($fileName)->inBucket(self::BUCKET_NAME)->execute();
        }
    }
}
